﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using VosSoft.ZuneLcd.Api;

namespace VosSoft.ZuneLcd.Color
{
    internal class TrackListBoxItem : ListBoxItem
    {
        internal Track Track { get; private set; }

        internal TrackListBoxItem(Track track)
        {
            Track = track;

            BitmapImage cover = null;
            if (!string.IsNullOrEmpty(track.CoverUrl))
            {
                try
                {
                    Uri coverUri = new Uri(track.CoverUrl, UriKind.Absolute);
                    if (System.IO.File.Exists(coverUri.LocalPath))
                    {
                        cover = new BitmapImage(coverUri);
                    }
                }
                catch (UriFormatException)
                {
                }
            }

            Border coverBorder = null;
            if (cover != null)
            {
                coverBorder = new Border()
                {
                    MaxWidth = MaxHeight = 26,
                    VerticalAlignment = VerticalAlignment.Center,
                    BorderThickness = new Thickness(1.0),
                    BorderBrush = Brushes.White,
                    Margin = new Thickness(0.0, 0.0, 4.0, 0.0),
                    Child = new Image()
                    {
                        Source = cover,
                    },
                    SnapsToDevicePixels = true
                };
            }

            StackPanel textPanel = new StackPanel()
            {
                Children = {
                    new TextBlock()
                    {
                        FontSize = 16.0,
                        FontWeight = FontWeights.Medium,
                        Text = track.Title,
                        Margin = new Thickness(0.0, -2.0, 0.0, 0.0),
                        TextTrimming = TextTrimming.CharacterEllipsis
                    },
                    new TextBlock()
                    {
                        FontSize = 12.0,
                        Foreground = Brushes.Silver,
                        Text = track.Artist.ToUpper(),
                        Margin = new Thickness(0.0, -4.0, 0.0, 0.0),
                        TextTrimming = TextTrimming.CharacterEllipsis
                    }
                },
                VerticalAlignment = VerticalAlignment.Center,
            };

            StackPanel container = new StackPanel()
            {
                Orientation = Orientation.Horizontal,
            };

            if (coverBorder != null)
                container.Children.Add(coverBorder);
            container.Children.Add(textPanel);

            AddChild(container);

            Margin = new Thickness(2.0);
        }
    }
}
